import { BadRequestException, Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { omit, pick } from 'lodash'
import { UserEntity } from '@/database/entities'
import { ICRUD } from '@/common/interfaces'
import {
  CreateUserDTO,
  FindUserDTO,
  PaginateUserDTO,
  UpdateUserDTO
} from './dtos'

@Injectable()
export class UserService implements ICRUD {
  constructor(
    @InjectRepository(UserEntity)
    private userRepository: Repository<UserEntity>
  ) {}

  async findOne(dto: FindUserDTO) {
    return await this.userRepository.findOne(dto)
  }

  async findMany(dto: FindUserDTO) {
    return await this.userRepository.find(dto)
  }

  async paginate(dto: PaginateUserDTO) {
    const where = omit(dto, ['pageNum', 'pageSize'])
    const { pageNum, pageSize } = pick(dto, ['pageNum', 'pageSize'])
    const [list, total] = await this.userRepository.findAndCount({
      where,
      take: pageSize,
      skip: pageNum - 1
    })

    return {
      pageNum,
      pageSize,
      total,
      list
    }
  }

  async createOne(dto: CreateUserDTO) {
    const existingUser = await this.userRepository.findOne({
      username: dto.username
    })

    if (existingUser) {
      throw new BadRequestException('创建失败，用户已存在')
    }

    await this.userRepository.save(dto)
  }

  async updateOne(id: number, dto: UpdateUserDTO) {
    const existingUser = await this.userRepository.findOne({ id })

    if (!existingUser) {
      throw new BadRequestException('更新失败，用户已存在')
    }

    existingUser.gender = dto.gender
    existingUser.age = dto.age
    existingUser.mobile = dto.mobile

    this.userRepository.save(existingUser)
  }

  async deleteOne(id: number) {
    await this.userRepository.delete(id)
  }

  async deleteMany(ids: number[]) {
    await this.userRepository.delete(ids)
  }
}
